import { useRouter } from 'next/router';
import { resourceMcp } from '@/client/api'
import { Button, Tabs, Switch, Tag, Tooltip, Collapse,Space,Input,Spin } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import React,{ useEffect, useState } from 'react';
import MyEmpty from '@/components/common/MyEmpty';
const { Panel } = Collapse;

const MCPDetailPage = ({setDetailPage}) => {
  const router = useRouter();
  const mcpInfo = JSON.parse(localStorage.getItem('new_mcp_info') || '{}');
  const [mcpResourceTabData,setMcpResourceData ] =  useState({status: true})
  const [loading, setLoading] = useState<boolean>(true);

  function convertFromJson(jsonString) {
      try {
          const obj = JSON.parse(jsonString);
          return Object.entries(obj)
              .map(([key, value]) => `${key}=${value}`)
              .join('\n');
      } catch (error) {
          console.error('Invalid JSON format:', error);
          return '';
      }
  }

  const getMcpResourceData = async ()=>{
      const res = await resourceMcp({id:mcpInfo.id});
      if(res.data.success){
        const mcpResourceInfo = res.data.data;
        
        mcpResourceInfo.tools.forEach(item=>{     
          const requiredArr = item.inputSchema.required || [];
          if(Object.keys(item.inputSchema.properties).length){
            const mcpTools = []
            for(const it in item.inputSchema.properties){
              // console.log(requiredArr,it,requiredArr.includes(it))
              mcpTools.push(
                {
                  key: it,
                  label: it,
                  type: item.inputSchema.properties[it].type,
                  desc: item.inputSchema.properties[it].description,      
                  required: requiredArr.includes(it) || false,         
                }
            )}     
            item.inputSchema = mcpTools
          }
        })

        if(mcpResourceInfo.mcp_config.type == 2){
          mcpResourceInfo.mcp_config.env = convertFromJson(mcpResourceInfo.mcp_config.env);
          mcpResourceInfo.mcp_config.args =  typeof mcpResourceInfo.mcp_config.args === 'string' && mcpResourceInfo.mcp_config.args
          ? mcpResourceInfo.mcp_config.args.replace(/,/g, '\n')
          : '';
        }

        setMcpResourceData(mcpResourceInfo)
        setLoading(false);
      }
  }

  useEffect( () => {
    getMcpResourceData()
  },[])

  return (
    <Spin spinning={loading} className="h-full">
      <div className='px-8 py-6'>
      {/* 顶部返回 */}
      <div className="flex items-center mb-4">
        <Button
          type="text"
          icon={<LeftOutlined />}
          onClick={() => setDetailPage(true) }
          style={{ marginRight: 8 }}
        />
        <span className="text-lg font-medium">{mcpResourceTabData?.mcp_config?.name}</span>      
        <Tag color="purple" className="ml-2">{mcpResourceTabData?.mcp_config?.type==1?"MCP-streamableHttp":mcpResourceTabData?.mcp_config?.type==2?"MCP-STDIO":"MCP-SSE"}</Tag>
        { !mcpResourceTabData?.status && <Tag color="red">连接已失效</Tag> }    
      </div>
      <div className="text-gray-400 text-sm mb-2">创建时间：{mcpResourceTabData?.mcp_config?.create_datetime}</div>
      <div className="mb-6 text-gray-600 text-base dark:text-white">
        服务简介：{mcpResourceTabData?.mcp_config?.desc}
      </div>

      <Tabs
        defaultActiveKey="apply"      
        className="bg-transparent"
      >
        <Tabs.TabPane tab="通用" key="apply">
         
          <Space direction="vertical" className='mt-4'>
            { mcpResourceTabData?.mcp_config?.type <=1 && (
              <>
                <span className='font-bold text-md'>MCP Server URL</span>
                <Tag className='p-3 text-sm'>{mcpResourceTabData?.mcp_config?.server_url}</Tag>
              </>
            )}
           { mcpResourceTabData?.mcp_config?.type ==2 && (
              <>
                <span className='font-bold text-md'>命令</span>
                <Tag className='p-2 text-sm'>{mcpResourceTabData?.mcp_config?.script || '-'}</Tag>
                <span className='font-bold text-md'>参数</span>
                { mcpResourceTabData?.mcp_config?.args ? <Input.TextArea autoSize={{ minRows: 2.5 }} readOnly value={mcpResourceTabData?.mcp_config?.args} /> : '-'}   
                <span className='font-bold text-md'>环境变量</span>
                { mcpResourceTabData?.mcp_config?.env ? <Input.TextArea autoSize={{ minRows: 2.5 }} readOnly value={mcpResourceTabData?.mcp_config?.env} /> :'-'}            
              </>
            )}
          </Space>        
        </Tabs.TabPane>
        <Tabs.TabPane tab="工具" key="tool">
            <div className='mt-4 overflow-auto' style={{ height: 650}}>
              <div className="text-lg font-semibold mb-2">可用工具</div>
              <Collapse className='bg-white dark:bg-[#1e1f2b]'>
                {mcpResourceTabData?.tools?.map(tool => (
                  <Panel
                    header={
                      <div className="w-full">
                          <div>
                            <span className="font-medium">{tool.name}</span>
                            {/* <span className="ml-2 text-xs text-gray-400">{tool.label}</span> */}
                          </div>                                        
                          <div className="text-gray-400 text-xs">{tool.description}</div>                      
                      </div>
                    }
                    key={tool.key}
                    className=''
                  >
                    {tool.inputSchema.length > 0 && (
                      <div>
                        <div className="font-medium mb-2">输入格式:</div>
                    
                        <div className="border rounded-lg overflow-hidden dark:border-[#444c5b]">
                          {tool.inputSchema.map((p, idx) => (
                            <div
                              key={p.key}
                              className={`flex items-center border-b last:border-b-0 dark:border-[#444c5b]`}                    
                            >
                              {/* 参数名 */}
                              <div className="w-1/4 h-full font-mono text-base flex items-center border-r bg-[#fafafa] dark:bg-black dark:border-r-[#444c5b]" style={{padding:20}}>
                                <span>
                                  {p.label}
                                  {p.required && <span style={{ color: '#f5222d', marginLeft: 2 }}>*</span>}
                                </span>
                              </div>

                              <div className="flex-1 text-gray-500 text-sm bg-white dark:text-white dark:bg-black" style={{padding:12}}>
                                <div className="flex items-center">
                                  { p.type === 'string' && <span className="inline-block w-2 h-2 rounded-full bg-blue-400 mr-2"></span>}
                                  <span className="text-gray-700 dark:text-white">{p.type}</span>
                                </div>
                                {p.desc}
                              </div>
                            </div>
                          ))}
                        </div>

                      </div>
                    )}
                  </Panel>
                ))}
              </Collapse>
            </div>
        </Tabs.TabPane>
        <Tabs.TabPane tab="提示词" key="prompt">
          <div className='mt-4 overflow-auto' style={{ height: 650}}>
              <div className="text-lg font-semibold mb-2">可用提示</div>
              { mcpResourceTabData?.prompts?.length == 0 && <MyEmpty description='暂无数据' /> }

              { mcpResourceTabData?.prompts?.length>0 && <Collapse className='bg-white dark:bg-[#1e1f2b]'>
                  {mcpResourceTabData?.prompts?.map(prompt => (
                    <Panel
                      header={
                        <div className="w-full">
                            <div>
                              <span className="font-medium">{prompt.name}</span>                          
                            </div>                                         
                            <div className="text-gray-400 text-xs">{prompt.description}</div>
                        </div>
                      }
                      key={prompt.name}
                      className=''
                    >
                      {prompt.arguments.length > 0 && (
                        <div className='h-full overflow-auto'>
                          <div className="font-medium mb-2">输入格式:</div>
                      
                          <div className="border rounded-lg overflow-hidden dark:border-[#444c5b]">
                            {prompt.arguments.map((p, idx) => (
                              <div
                                key={p.name}
                                className={`flex items-center border-b last:border-b-0 dark:border-[#444c5b]`}                    
                              >
                                {/* 参数名 */}
                                <div className="w-1/4 h-full font-mono text-base flex items-center border-r bg-[#fafafa] dark:bg-black dark:border-r-[#444c5b]" style={{padding:20}}>
                                  <span>
                                    {p.name}
                                    {p.required && <span style={{ color: '#f5222d', marginLeft: 2 }}>*</span>}
                                  </span>
                                </div>

                                <div className="flex-1 text-gray-500 text-sm bg-white dark:text-white dark:bg-black" style={{padding:22}}>                               
                                  {p.description}
                                </div>
                              </div>
                            ))}
                          </div>

                        </div>
                      )}
                    </Panel>
                  ))}
                </Collapse>
              }
            </div>
        </Tabs.TabPane>
        <Tabs.TabPane tab="资源" key="resource">
          <div className='mt-4 overflow-auto' style={{ height: 650}}>
              <div className="text-lg font-semibold mb-2">可用资源</div>
              { mcpResourceTabData?.resources?.length == 0 && <MyEmpty description='暂无数据' /> }
          </div>
        </Tabs.TabPane>
      </Tabs>
      </div>
    </Spin>
  );
};

export default MCPDetailPage;